package itesm.coler.datastorage;

import itesm.coler.models.User;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.jdo.Transaction;

public class UserDAO {

	private static final Logger log = Logger.getLogger(UserDAO.class.getName()); // hacer

	// el
	// logger

	// Method to insert a new user
	public static void insertUser(User user) {

		// LLamamos a la clase que tendra la persistencia
		PersistenceManager pm = null;

		// Haciendo la persistencia de datos
		pm = PMF.get().getPersistenceManager();
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			pm.makePersistent(user);
			tx.commit();
			log.info("transaction commit");
		} catch (Exception e) {
			log.warning(e.getMessage());
		} finally {
			if (tx.isActive()) {
				tx.rollback();
				log.warning("did transaction rollback");
			}
			if (pm != null)
				pm.close();
		}
	}

	public static User getUserByUserName(String userName) {
		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			User user = pm.getObjectById(User.class, userName);
			log.warning("usuario obtenido");
			log.info("usuario obtenido");
			return user;
		} catch (Exception e) {
			log.warning(e.getMessage());
			log.info(e.getMessage());
			throw new RuntimeException(e);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	// Method to return the list of users
	public static List<User> getUsersList() {
		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery("select from " + User.class.getName()
					+ "");
			List<User> users = (List<User>) query.execute();
			users.size(); // es necesario agregarlo debido a bug -
			// http://www.atentia.net/2010/03/app-engine-and-jdo-object-manager-has-been-closed/
			return users;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<String> getUsernames() {
		PersistenceManager pm = null;
		try {
			pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery("select userName from "
					+ User.class.getName() + "");
			List<String> users = (List<String>) query.execute();
			users.size(); // es necesario agregarlo debido a bug -
			// http://www.atentia.net/2010/03/app-engine-and-jdo-object-manager-has-been-closed/
			log.info("Finished retrieving user names.");
			log.warning("Finished retrieving user names.");
			return users;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (pm != null)
				pm.close();
		}
	}

}
